﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using MLY.Bll;
using System.Drawing;
using System.Web.UI.DataVisualization.Charting;

namespace MLY.Reports.ChartReports
{
    public partial class DisqualifyReasonsReport : System.Web.UI.Page
    {
        public class DisqualifyReasonsReportData
        {
            public string ReasonName { get; set; }
            public decimal Total { get; set; }
            public decimal Disqualified { get; set; }

            public decimal Percentage()
            {
                if (Total > 0)
                    return decimal.Truncate(Disqualified / Total);
                return 0;
            }

        }

        public static int IDNum = 1;

        public class DisqualifyReasonDict
        {
            public int ReasonId { get; set; }
            public string ReasonName { get; set; }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (SessParam.IsClient)
            {
                ReportGrid.Columns[3].Visible = false;
                ReportGrid.Columns[4].Visible = false;
            }
            else
            {
                ReportGrid.Columns[1].Visible = false;
                ReportGrid.Columns[2].Visible = false;
            }

            if (clsUser.CurrentUserRoleId < 0)
            {
                Response.RedirectTo("/LTR/Login.aspx?ReturnTo=" + Request.Url.ToString());
            }

            // direction
            if (SessParam.Culture == "he")
            {
                //cssLiteral.Text = @"<link type=""text/css"" rel=""stylesheet"" href=""/Style/Rtl_Stylesheet.css"" />";
                ReportDefinitionsPanel.Direction = ContentDirection.RightToLeft;
                ReportPanel.Direction = ContentDirection.RightToLeft;
            }
            else
            {
                //cssLiteral.Text = @"<link type=""text/css"" rel=""stylesheet"" href=""/Style/Ltr_Stylesheet.css"" />";
                ReportDefinitionsPanel.Direction = ContentDirection.LeftToRight;
                ReportPanel.Direction = ContentDirection.LeftToRight;
            }           
            
        }

        protected void ddlOrgs_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ddlOrgs.Items.Clear();
                ListItem all = new ListItem("All", "0");
                ddlOrgs.Items.Add(all);
                ddlOrgs.AppendDataBoundItems = true;

                if (SessParam.IsClient)
                {
                    ddlOrgs.DataSource = MLY.Bll.clsOrganization.GetContractorsByClientId((int)Session["OrganizationId"]);
                    ddlOrgs.DataBind();
                }
                else
                {
                    ddlOrgs.DataSource = MLY.Bll.clsOrganization.GetClientsByContractorId((int)Session["OrganizationId"]);
                    ddlOrgs.DataBind();
                }
            }
        }

        


        protected void ReasonsListLoad(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DisqualifyReasonsDDL.Items.Clear();
                DisqualifyReasonsDDL.Items.Add(new ListItem(Dictionary.Translate("reportsParams.AllReasons"), "0"));

                using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
                {
                    SqlCommand cmd = new SqlCommand("SCCOver_GetCancelReasons", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlDataReader reader;

                    cmd.Parameters.Add("OrganizationId", SqlDbType.Int);
                    cmd.Parameters["OrganizationId"].Value = SessParam.OrganizationId;

                    try
                    {
                        conn.Open();
                        reader = cmd.ExecuteReader();
                        if (reader.HasRows)
                            while (reader.Read())
                            {
                                DisqualifyReasonDict rd = new DisqualifyReasonDict();
                                rd.ReasonId = reader.GetInt32(0);
                                rd.ReasonName = reader.GetString(1);

                                DisqualifyReasonsDDL.Items.Add(new ListItem(rd.ReasonName, rd.ReasonId.ToString()));
                            }
                    }
                    catch (Exception ex)
                    {
                        Log.WriteError(ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }

                }
            }
        }

        protected void GenerateReport(object sender, EventArgs e)
        {
            try
            {
                string From = Utils.SqlDate(DateTime.Parse(txtFromDate.Text.Trim()));
                string Till = Utils.SqlDate(DateTime.Parse(txtToDate.Text.Trim()));

                ReportPanel.Visible = true;
                RowDisqualifyDataSource.SelectParameters.Clear();
                RowDisqualifyDataSource.SelectParameters.Add("UserOrgId", SessParam.OrganizationId.ToString());
                RowDisqualifyDataSource.SelectParameters.Add("PartnerOrgId", ddlOrgs.SelectedValue);
                RowDisqualifyDataSource.SelectParameters.Add("IsClient", SessParam.IsClient ? "1" : "0");
                RowDisqualifyDataSource.SelectParameters.Add("DateType", DateTypesDDL.SelectedValue);
                RowDisqualifyDataSource.SelectParameters.Add("DateStart", From);
                RowDisqualifyDataSource.SelectParameters.Add("DateEnd", Till);
                RowDisqualifyDataSource.SelectParameters.Add("Reason", DisqualifyReasonsDDL.SelectedValue);
                RowDisqualifyDataSource.SelectParameters.Add("QCStage", QCStageDDL.SelectedValue);

                ReportGrid.DataBind();
            }
            catch (Exception ex)
            {
                Log.WriteError(ex.Message);
            }

            LoadPieChart();
            LoadOrgsChart();
            LoadTrendChart();
        }

        protected void btnXlsExport_Click(object sender, EventArgs e)
        {
            Response.Clear();
            gridExport.WriteXlsToResponse();

        }
        protected void btnXlsxExport_Click(object sender, EventArgs e)
        {
            Response.Clear();
            gridExport.WriteXlsxToResponse();
        }
        protected void btnRtfExport_Click(object sender, EventArgs e)
        {
            Response.Clear();
            gridExport.WriteRtfToResponse();
        }
        protected void btnCsvExport_Click(object sender, EventArgs e)
        {
            gridExport.WriteCsvToResponse();
        }

        private void LoadPieChart()
        {
            string ReasonName = "", ReasonShort= "";

            decimal Quantity = 0, TotalQuantity = 0;
            int pointNum;
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("SCCover_DisqualifyReasonReport", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader reader;

                cmd.Parameters.Add("CatalogueCode", SqlDbType.NVarChar, 50);
                cmd.Parameters.Add("UserOrgId", SqlDbType.Int);
                cmd.Parameters.Add("PartnerOrgId", SqlDbType.Int);
                cmd.Parameters.Add("IsClient", SqlDbType.Bit);
                cmd.Parameters.Add("DateType", SqlDbType.Int);
                cmd.Parameters.Add("DateStart", SqlDbType.DateTime);
                cmd.Parameters.Add("DateEnd", SqlDbType.DateTime);
                cmd.Parameters.Add("DisqualifyReason", SqlDbType.Int);
                cmd.Parameters.Add("QCStage", SqlDbType.Int);

                cmd.Parameters["CatalogueCode"].Value = "";
                cmd.Parameters["UserOrgId"].Value = SessParam.OrganizationId ;
                cmd.Parameters["PartnerOrgId"].Value = ddlOrgs.SelectedValue;
                cmd.Parameters["IsClient"].Value = SessParam.IsClient;
                cmd.Parameters["DateType"].Value = DateTypesDDL.SelectedValue ;
                cmd.Parameters["DateStart"].Value = Utils.SqlDate(DateTime.Parse(txtFromDate.Text.Trim()));
                cmd.Parameters["DateEnd"].Value = Utils.SqlDate(DateTime.Parse(txtToDate.Text.Trim()));
                cmd.Parameters["DisqualifyReason"].Value = DisqualifyReasonsDDL.SelectedValue;
                cmd.Parameters["QCStage"].Value = QCStageDDL.SelectedValue;

                DisqualifyReasonsChart.Series[0].Points.Clear();

                try
                {
                    conn.Open();
                    reader = cmd.ExecuteReader();
                    if (reader.HasRows) 
                        while (reader.Read())
                        {
                            ReasonName = reader.GetString(0);
                            
                            if (ReasonName.Length > 15) ReasonShort = ReasonName.Substring(0, 15) + "...";
                            else ReasonShort = ReasonName;

                            TotalQuantity = reader.GetDecimal(1);
                            Quantity = reader.GetDecimal(2);
                            if (Quantity > 0)
                            {
                                pointNum = DisqualifyReasonsChart.Series[0].Points.AddXY(ReasonShort, Quantity);
                                DisqualifyReasonsChart.Series[0].Points[pointNum].ToolTip = ReasonName;
                            }
                        }
                }
                catch (Exception ex)
                {
                    Log.WriteError(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
            }

        }

        private void LoadOrgsChart()
        {
            //if (ddlOrgs.SelectedValue == "0")
            //{
                using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
                {
                    string OrgName = "";
                    decimal TotalQty = 0, DisqualifiedQty = 0;
                    int index = 0;
                    int titlestart = 1;
                    
                    SqlCommand cmd = new SqlCommand("SCCover_DisqualifyByOrganization", conn);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("CatalogueCode", SqlDbType.NVarChar, 50);
                    cmd.Parameters.Add("UserOrgId", SqlDbType.Int);
                    cmd.Parameters.Add("PartnerOrgId", SqlDbType.Int);
                    cmd.Parameters.Add("IsClient", SqlDbType.Bit);
                    cmd.Parameters.Add("DateType", SqlDbType.Int);
                    cmd.Parameters.Add("DateStart", SqlDbType.DateTime);
                    cmd.Parameters.Add("DateEnd", SqlDbType.DateTime);
                    cmd.Parameters.Add("DisqualifyReason", SqlDbType.Int);

                    cmd.Parameters["CatalogueCode"].Value = "";
                    cmd.Parameters["UserOrgId"].Value = SessParam.OrganizationId;
                    cmd.Parameters["PartnerOrgId"].Value = ddlOrgs.SelectedValue;
                    cmd.Parameters["IsClient"].Value = SessParam.IsClient;
                    cmd.Parameters["DateType"].Value = DateTypesDDL.SelectedValue;
                    cmd.Parameters["DateStart"].Value = Utils.SqlDate(DateTime.Parse(txtFromDate.Text.Trim()));
                    cmd.Parameters["DateEnd"].Value = Utils.SqlDate(DateTime.Parse(txtToDate.Text.Trim()));
                    cmd.Parameters["DisqualifyReason"].Value = DisqualifyReasonsDDL.SelectedValue;

                    SqlDataReader reader;
                    try
                    {
                        conn.Open();
                        reader = cmd.ExecuteReader();
                        
                        //OrgsChart.Series[0].Points.Clear();
                        //OrgsChart.Series[1].Points.Clear();
                        if (reader.HasRows)
                        {
                            Chart OrgsChart = NewOrgsChart();
                            
                            while (reader.Read())
                            {
                                index++;
                                OrgName = reader.GetString(0);
                                TotalQty = reader.GetDecimal(1);
                                DisqualifiedQty = reader.GetDecimal(2);

                                OrgsChart.Series[0].Points.AddXY(index, System.Convert.ToDouble(TotalQty));
                                OrgsChart.Series[1].Points.AddXY(index, System.Convert.ToDouble(DisqualifiedQty));
                                System.Web.UI.DataVisualization.Charting.CustomLabel CustomLabel =
                                    new System.Web.UI.DataVisualization.Charting.CustomLabel
                                    {
                                        Text = OrgName,
                                        FromPosition = index - 0.5,
                                        ToPosition = index + 0.5
                                    };
                                OrgsChart.ChartAreas["ChartArea1"].AxisX.CustomLabels.Add(CustomLabel);

                                if (index % 10 == 0)
                                {
                                    OrgsChart.Titles[0].Text += (" " + titlestart.ToString() + " - " + index.ToString());
                                    titlestart = index + 1;
                                    OrgChartsContainer.Controls.Add(OrgsChart);

                                    Label BR = new Label();
                                    BR.Text = "<br />";
                                    BR.ID = "BRLabel" + IDNum.ToString();
                                    IDNum++; 
                                    OrgChartsContainer.Controls.Add(BR);

                                    OrgsChart = NewOrgsChart();
                                }
                            }
                            if (index % 10 != 0)
                            {
                                if (index > 10)
                                {
                                    OrgsChart.Titles[0].Text += (" " + titlestart.ToString() + " - " + index.ToString());
                                }
                                OrgChartsContainer.Controls.Add(OrgsChart);
                                
                                Label BR = new Label();
                                BR.Text = "<br />";
                                BR.ID = "BRLabel" + IDNum.ToString();
                                IDNum++;
                                
                                OrgChartsContainer.Controls.Add(BR);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.WriteError(ex.Message);
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            //}
            //else
            //{
            //    OrgsChart.Visible = false;
            //}
        }

        private Chart NewOrgsChart()
        {
            Chart orgChart = new Chart();
            orgChart.ID = "orgChart" + IDNum.ToString();
            IDNum++;

            Series original_quantity_series = new Series(Dictionary.Translate("clientAddWo.OriginalQuantity"));
            Series disqualifier_quantity_series = new Series(Dictionary.Translate("reports.DisqualifiedQuantity"));
            Title title1 = new Title(Dictionary.Translate("OrgsGrid.Title"), Docking.Top, new Font("Trebuchet MS", 10, System.Drawing.FontStyle.Bold), System.Drawing.Color.Black);
            Legend legend1 = new Legend("Default");
            ChartArea chartArea1 = new ChartArea("ChartArea1");
            
            orgChart.Width = Unit.Pixel(800);
            orgChart.Height = Unit.Pixel(320);
            orgChart.ImageLocation = "~/Images/OrgsChart" + IDNum.ToString();
            orgChart.ImageStorageMode = ImageStorageMode.UseImageLocation;
            orgChart.ImageType = ChartImageType.Png;

            title1.Alignment = ContentAlignment.TopCenter;
            title1.Font = new Font("Arial", 14, System.Drawing.FontStyle.Bold);
            title1.ShadowColor = Color.FromArgb(32, 0, 0, 0);
            title1.ShadowOffset = 3;
            title1.ForeColor = Color.Blue;
            orgChart.Titles.Add(title1);

            legend1.IsTextAutoFit = true;
            legend1.Font = new Font("Arial", 10, FontStyle.Bold);
            legend1.Docking = Docking.Right;
            orgChart.Legends.Add(legend1);

            chartArea1.BorderColor = System.Drawing.Color.FromArgb(64, 64, 64, 64);
            chartArea1.BorderDashStyle = ChartDashStyle.Solid;
            chartArea1.BackSecondaryColor = Color.White;
            chartArea1.BackColor = Color.Gainsboro;
            chartArea1.ShadowColor = Color.Transparent;
            chartArea1.BackGradientStyle = GradientStyle.TopBottom;
            
            chartArea1.Area3DStyle.Rotation = 10;
            chartArea1.Area3DStyle.Inclination = 15;
            chartArea1.Area3DStyle.IsRightAngleAxes = false;
            chartArea1.Area3DStyle.WallWidth = 0;
            chartArea1.Area3DStyle.IsClustered = false;

            chartArea1.AxisY.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea1.AxisY.IsLabelAutoFit = false;
            chartArea1.AxisY.LabelStyle.Font = new Font("Arial", 8, FontStyle.Bold);
            chartArea1.AxisY.LabelStyle.IsStaggered = true;
            chartArea1.AxisY.MajorGrid.LineColor = Color.FromArgb(32, 32, 32, 32);

            chartArea1.AxisX.LineColor = Color.FromArgb(64, 64, 64, 64);
            chartArea1.AxisX.IsLabelAutoFit = false;
            chartArea1.AxisX.LabelStyle.Font = new Font("Arial", 8, FontStyle.Bold);
            chartArea1.AxisX.MajorGrid.LineColor = Color.FromArgb(32, 32, 32, 32);

            original_quantity_series.IsValueShownAsLabel = true;
            original_quantity_series.ShadowColor = Color.Gray;
            original_quantity_series.ShadowOffset = 1;

            disqualifier_quantity_series.IsValueShownAsLabel = true;
            disqualifier_quantity_series.ShadowColor = Color.Gray;
            disqualifier_quantity_series.ShadowOffset = 1;

            orgChart.ChartAreas.Add(chartArea1);
            orgChart.Series.Add(original_quantity_series);
            orgChart.Series.Add(disqualifier_quantity_series);

            
            return orgChart;            
        }



        private void LoadTrendChart()
        {
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MLYConnectionString"].ConnectionString))
            {
                int index = 0;
                SqlCommand cmd = new SqlCommand("SCCover_DisqualifyTrendsReport", conn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add("CatalogueCode", SqlDbType.NVarChar, 50);
                cmd.Parameters.Add("UserOrgId", SqlDbType.Int);
                cmd.Parameters.Add("PartnerOrgId", SqlDbType.Int);
                cmd.Parameters.Add("IsClient", SqlDbType.Bit);
                cmd.Parameters.Add("DateType", SqlDbType.Int);
                cmd.Parameters.Add("DateStart", SqlDbType.DateTime);
                cmd.Parameters.Add("DateEnd", SqlDbType.DateTime);
                cmd.Parameters.Add("DisqualifyReason", SqlDbType.Int);
                cmd.Parameters.Add("TrendType", SqlDbType.Int);
                cmd.Parameters.Add("QCStage", SqlDbType.Int);

                cmd.Parameters["CatalogueCode"].Value = "";
                cmd.Parameters["UserOrgId"].Value = SessParam.OrganizationId;
                cmd.Parameters["PartnerOrgId"].Value = ddlOrgs.SelectedValue;
                cmd.Parameters["IsClient"].Value = SessParam.IsClient;
                cmd.Parameters["DateType"].Value = DateTypesDDL.SelectedValue;
                cmd.Parameters["DateStart"].Value = Utils.SqlDate(DateTime.Parse(txtFromDate.Text.Trim()));
                cmd.Parameters["DateEnd"].Value = Utils.SqlDate(DateTime.Parse(txtToDate.Text.Trim()));
                cmd.Parameters["DisqualifyReason"].Value = DisqualifyReasonsDDL.SelectedValue;
                cmd.Parameters["TrendType"].Value = TrendsDDL.SelectedValue;
                cmd.Parameters["QCStage"].Value =  QCStageDDL.SelectedValue;

                SqlDataReader reader;

                try
                {
                    conn.Open();
                    reader = cmd.ExecuteReader();
                    TrendsChart.Series[0].Points.Clear();
                    if(reader.HasRows)
                        while (reader.Read())
                        { 
                            index ++;
                            System.Web.UI.DataVisualization.Charting.CustomLabel CustomLabel =
                                new System.Web.UI.DataVisualization.Charting.CustomLabel
                                {
                                    Text = reader.GetString(0),
                                    FromPosition = index - 0.5,
                                    ToPosition = index + 0.5
                                };
                            TrendsChart.ChartAreas[0].AxisX.CustomLabels.Add(CustomLabel);
                            TrendsChart.Series[0].Points.AddXY(index, System.Convert.ToDouble(reader.GetDecimal(1)));
                        }
                }
                catch (Exception ex)
                {
                    Log.WriteError(ex.Message);
                }
                finally
                {
                    conn.Close();
                }
            }
        }
    }
}
